/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.snda.lidejia.mongodbtest;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 *
 * @author lidejia
 */
public class Query {

    private static int THREAD_NUM = 50;
    private static final String HOST = "10.1.9.97";
    private static long TO = 1000000L;
    private static long FROM = 0L;

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws Exception {
        if (args.length == 3) {
            THREAD_NUM = Integer.parseInt(args[0]);
            FROM = Long.parseLong(args[1]);
            TO = Long.parseLong(args[2]);
        }
        System.out.println(String.format("Thread number is %s", THREAD_NUM));
        System.out.println(String.format("Query range is from %s to %s", FROM, TO));
        //
        System.setProperty("MONGO.POOLSIZE", Integer.toString(THREAD_NUM));
        //
        ExecutorService es = Executors.newCachedThreadPool();
        final CountDownLatch activeThreadCounter = new CountDownLatch(THREAD_NUM);
        final Mongo mongo = new Mongo(HOST);
        try {
            for (int i = 0; i < THREAD_NUM; i++) {
                es.execute(new Runnable() {

                    public void run() {
                        try {
                            DB db = mongo.getDB("test");
                            DBCollection collection = db.getCollection("test");
                            Random random = new Random();
                            while (true) {
                                BasicDBObject primaryKey = new BasicDBObject();
                                long id = (random.nextLong() % (TO - FROM)) + FROM;
                                primaryKey.put("_id", id);
                                DBObject result = collection.findOne(primaryKey);
                            }
                        } finally {
                            activeThreadCounter.countDown();
                        }
                    }
                });
            }
            es.shutdown();
            activeThreadCounter.await();
        } finally {
            mongo.close();
        }
    }
}
